package ipmsg.gui;

import ipmsg.etc.GlobalVar;
import java.awt.Component;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;

public class UtilityGui {
	public static boolean newWindow(String to, String msgContent, String from) {
		if (to == null) {
			MsgWindow win;
			if ((win = GlobalVar.getWindow("broadcast")) != null) {
				if (msgContent != null)
					win.appendNewMsg(msgContent, from);
				return false;
			}

			new MsgWindow(null, msgContent, from).setVisible(true);
		} else {
			MsgWindow win;
			if ((win = GlobalVar.getWindow(to)) != null) {
				if (msgContent != null)
					win.appendNewMsg(msgContent, from);
				return false;
			}

			new MsgWindow(to, msgContent, from).setVisible(true);
		}

		return true;
	}

	public static void setIcon(JFrame frame) {
		ImageIcon icon = new ImageIcon(frame.getClass().getResource("/lanmsg_v2/resource/logo.png"));

		frame.setIconImage(icon.getImage());
	}

	public static String getInputString(Component cpnt, String title, String tip, int maxLen) {
		int messagetype = 1;
		String res = null;
		do {
			res = JOptionPane.showInputDialog(cpnt, title, tip, messagetype);
			if (res == null)
				return null;
		} while ((res.trim().isEmpty()) || (res.trim().length() > maxLen));
		return res.trim();
	}

	public static void showNotice(Component cpnt, String content) {
		JOptionPane.showMessageDialog(cpnt, "\n" + content + "\n");
	}

	public static boolean confirm(Component cpnt, String title, String tip) {
		if (JOptionPane.showConfirmDialog(cpnt, tip, title, 2, 3, null) == 2) {
			return false;
		}
		return true;
	}

	public static String chooseFile(JFrame frame, boolean file) {
		JFileChooser chooser = new JFileChooser();

		if (file)
			chooser.setFileSelectionMode(0);
		else
			chooser.setFileSelectionMode(1);
		int returnVal = chooser.showOpenDialog(frame);
		if (returnVal == 0)
			return chooser.getSelectedFile().getPath();
		return null;
	}

	public static File[] chooseFile(JFrame frame) {
		JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode(2);

		chooser.setMultiSelectionEnabled(true);
		int returnVal = chooser.showOpenDialog(frame);

		if (returnVal == 0) {
			return chooser.getSelectedFiles();
		}
		return null;
	}

	public static String getPasswd(JFrame frame, String noteMsg, String title) {
		JPasswordField pwd = new JPasswordField();
		Object[] message = { noteMsg, pwd };
		for (;;) {
			int res = JOptionPane.showConfirmDialog(frame, message, title, 2, 3);

			if (res != 0)
				break;
			String passwd;
			if (((passwd = new String(pwd.getPassword())) != null) && (!passwd.equals(""))) {
				return passwd;
			}
		}

		return null;
	}
}
